package org.example.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.example.system.common.base.BasePageQuery;
import org.example.system.common.result.Result;
import org.example.system.model.entity.BizModel;
import org.example.system.model.form.BizModelForm;
import org.example.system.model.query.*;
import org.example.system.model.vo.PageVo;
import org.example.system.service.BizModelService;
import org.example.system.service.VehicleService;
import org.example.system.service.impl.BizModelServiceImpl;
import org.modelmapper.ModelMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Tag(name = "13.车型管理表")
@RestController
@RequestMapping("/api/v1/model")
@RequiredArgsConstructor
//@Slf4j
public class BizModelController {
    @Resource
    private BizModelService carModelService;

    @Resource
    private BizModelServiceImpl bizModelService;
    @Resource
    private ModelMapper modelMapper;

    @Resource
    private VehicleService vehicleService;


    @Operation(summary = "车型列表")
    @PostMapping("/model/list")
    public Result queryModelByPage(@RequestBody ModelPageQuery modelPageQuery)  {
        LambdaQueryWrapper<BizModel> criteria = new LambdaQueryWrapper<>();
        if(StringUtils.hasLength(modelPageQuery.getKeywords())){
            criteria.and(wrap->wrap.like(BizModel::getModelName,modelPageQuery.getKeywords())
                    .or().like(BizModel::getModelType,modelPageQuery.getKeywords())
                    .or().like(BizModel::getSeatNumber,modelPageQuery.getKeywords())
                    .or().like(BizModel::getDisplacement,modelPageQuery.getKeywords())
                    .or().like(BizModel::getGear,modelPageQuery.getKeywords())
                    .or().like(BizModel::getFuelType,modelPageQuery.getKeywords())
                    .or().like(BizModel::getFuelLabel,modelPageQuery.getKeywords())
                    .or().like(BizModel::getDailyRent,modelPageQuery.getKeywords())
                    .or().like(BizModel::getDepositAmount,modelPageQuery.getKeywords()));
        }
        criteria.orderByDesc(BizModel::getCreateTime);//按创建时间倒序排序
        if(modelPageQuery.getPageSize()>20){
            modelPageQuery.setPageSize(20);
        }
        int pageNum = modelPageQuery.getPageNum();
        int pageSize = modelPageQuery.getPageSize();
        Page<BizModel> page = new Page<>(pageNum, pageSize);
        Page<BizModel> bizModelPage = carModelService.page(page, criteria);
        PageVo pageVo = new PageVo();
        pageVo.setTotal(bizModelPage.getTotal());
        pageVo.setList(bizModelPage.getRecords());
        // 判断是否查询到数据，如果总记录数为0，则返回失败结果
        if (bizModelPage.getTotal() == 0) {
            return Result.failed("未查询到符合条件的车型数据");
        }
        return Result.success(pageVo);
    }
    @Operation(summary="新增车型")
    @PostMapping("/add")
    public Result add(@RequestBody BizModelForm bizModelForm){

        BizModel modelPo = modelMapper.map(bizModelForm, BizModel.class);
        carModelService.save(modelPo);
        return Result.success("新增车型成功");
    }
    @Operation(summary="删除车型")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        BizModel model = carModelService.getById(id);
        if (model == null) {
            return Result.failed("指定的车型不存在");
        }
        carModelService.removeById(id);
        return Result.success("删除车型成功");
    }
    @Operation(summary="修改车型信息")
    @PutMapping("/update")
    public Result update(@RequestBody BizModelForm bizModelForm){
        BizModel modelPo = modelMapper.map(bizModelForm, BizModel.class);
        modelPo.setUpdateTime(LocalDateTime.now());
        carModelService.updateById(modelPo);
        return Result.success("修改车型信息成功");
    }

    @Operation(summary="根据租金正序查询")
    @PostMapping("/DailyRentAsc")
    public Result DailyRentAsc(@RequestBody BasePageQuery basePageQuery) {
        QueryWrapper<BizModel> qw = new QueryWrapper<>();
        qw.orderByAsc("daily_rent");
        int pageNum = basePageQuery.getPageNum();
        int pageSize = basePageQuery.getPageSize();
        Page<BizModel> page = new Page<>(pageNum, pageSize);
        // 分页查询结果
        Page<BizModel> rentAscPage = carModelService.page(page, qw);
        PageVo pageVo = new PageVo();
        pageVo.setTotal(rentAscPage.getTotal());
        pageVo.setList(rentAscPage.getRecords());
        // 判断是否查询到数据，如果总记录数为0，则返回失败结果
        if (rentAscPage.getTotal() == 0) {
            return Result.failed("未查询到符合条件的车型数据");
        }
        return Result.success(pageVo);
    }


    @Operation(summary="根据租金倒序查询")
    @PostMapping("/DailyRentDesc")
    public Result DailyRentDesc(@RequestBody BasePageQuery basePageQuery) {
        QueryWrapper<BizModel> qw = new QueryWrapper<>();
        qw.orderByDesc("daily_rent");
        int pageNum = basePageQuery.getPageNum();
        int pageSize = basePageQuery.getPageSize();
        Page<BizModel> page = new Page<>(pageNum, pageSize);
        // 分页查询结果
        Page<BizModel> rentDescPage = carModelService.page(page, qw);
        PageVo pageVo = new PageVo();
        pageVo.setTotal(rentDescPage.getTotal());
        pageVo.setList(rentDescPage.getRecords());
        // 判断是否查询到数据，如果总记录数为0，则返回失败结果
        if (rentDescPage.getTotal() == 0) {
            return Result.failed("未查询到符合条件的车型数据");
        }
        return Result.success(pageVo);
    }

    @Operation(summary="根据日租金范围查询")
    @PostMapping("/DailyRentalRange")
    public Result DailyRentalRange(@RequestBody RentalRangeQuery rentalRangeQuery) {
        // 获取前端传入的日租金最小值和最大值
        int minRent = rentalRangeQuery.getMinRent();
        int maxRent = rentalRangeQuery.getMaxRent();

        LambdaQueryWrapper<BizModel> queryWrapper = new LambdaQueryWrapper<>();
        // 添加日租金范围查询条件
        queryWrapper.between(BizModel::getDailyRent, minRent, maxRent);
        // 添加按照日租金倒序排序的条件
        queryWrapper.orderByAsc(BizModel::getDailyRent);
        int pageNum = rentalRangeQuery.getPageNum();
        int pageSize = rentalRangeQuery.getPageSize();
        Page<BizModel> page = new Page<>(pageNum, pageSize);
        // 执行分页查询
        Page<BizModel> RentalRangePage = carModelService.page(page, queryWrapper);
        // 返回分页结果
        PageVo pageVo = new PageVo();
        pageVo.setTotal(RentalRangePage.getTotal());
        pageVo.setList(RentalRangePage.getRecords());
        // 判断是否查询到数据，如果总记录数为0，则返回失败结果
        if (RentalRangePage.getTotal() == 0) {
            return Result.failed("未查询到符合条件的车型数据");
        }
        return Result.success(pageVo);
    }
    @Operation(summary="根据车辆类型分页查询")
    @PostMapping("/modelType")
    public Result queryModelTypeByPage(@RequestBody ModelTypeQuery modelTypeQuery) {
        LambdaQueryWrapper<BizModel> criteria = new LambdaQueryWrapper<>();
        // 车辆类型查询条件
        criteria.like(BizModel::getModelType, modelTypeQuery.getModelType());
        // 执行分页查询
        int pageNum = modelTypeQuery.getPageNum();
        int pageSize = modelTypeQuery.getPageSize();
        Page<BizModel> page = new Page<>(pageNum, pageSize);
        Page<BizModel> modelTypePage = carModelService.page(page, criteria);
        PageVo pageVo = new PageVo();
        pageVo.setTotal(modelTypePage.getTotal());
        pageVo.setList(modelTypePage.getRecords());
        // 判断是否查询到数据，如果总记录数为0，则返回失败结果
        if (modelTypePage.getTotal() == 0) {
            return Result.failed("未查询到符合条件的车型数据");

        }
        return Result.success(pageVo);
    }
    @Operation(summary="车型多条件查询")
    @PostMapping("/serch")
    public Result queryByConditions(@RequestBody ModelMultiConditionQuery modelMultiConditionQuery) {
        LambdaQueryWrapper<BizModel> queryWrapper = new LambdaQueryWrapper<>();

        // 根据车型名称模糊查询
        if (modelMultiConditionQuery.getModelName()!= null &&!modelMultiConditionQuery.getModelName().isEmpty()) {
            queryWrapper.like(BizModel::getModelName, modelMultiConditionQuery.getModelName());
        }

        // 根据车辆类型模糊查询
        if (modelMultiConditionQuery.getModelType()!= null &&!modelMultiConditionQuery.getModelType().isEmpty()) {
            queryWrapper.like(BizModel::getModelType, modelMultiConditionQuery.getModelType());
        }

        // 根据座位数精确查询
        if (modelMultiConditionQuery.getSeatNumber()!= null) {
            queryWrapper.eq(BizModel::getSeatNumber, modelMultiConditionQuery.getSeatNumber());
        }

        // 根据排量模糊查询
        if (modelMultiConditionQuery.getDisplacement()!= null &&!modelMultiConditionQuery.getDisplacement().isEmpty()) {
            queryWrapper.like(BizModel::getDisplacement, modelMultiConditionQuery.getDisplacement());
        }

        // 根据挡位类型模糊查询
        if (modelMultiConditionQuery.getGear()!= null &&!modelMultiConditionQuery.getGear().isEmpty()) {
            queryWrapper.like(BizModel::getGear, modelMultiConditionQuery.getGear());
        }

        // 根据燃料类型模糊查询
        if (modelMultiConditionQuery.getFuelType()!= null &&!modelMultiConditionQuery.getFuelType().isEmpty()) {
            queryWrapper.like(BizModel::getFuelType, modelMultiConditionQuery.getFuelType());
        }

        // 根据燃油标号模糊查询
        if (modelMultiConditionQuery.getFuelLabel()!= null &&!modelMultiConditionQuery.getFuelLabel().isEmpty()) {
            queryWrapper.like(BizModel::getFuelLabel, modelMultiConditionQuery.getFuelLabel());
        }

        // 根据日租金范围查询
        if (modelMultiConditionQuery.getDailyRent()!= null) {
            BigDecimal minRent = modelMultiConditionQuery.getDailyRent().min(modelMultiConditionQuery.getDailyRent());
            BigDecimal maxRent = modelMultiConditionQuery.getDailyRent().max(modelMultiConditionQuery.getDailyRent());
            queryWrapper.between(BizModel::getDailyRent, minRent, maxRent);
        }
        // 根据押金金额范围查询
        if (modelMultiConditionQuery.getDepositAmount()!= null) {
            BigDecimal minDeposit = modelMultiConditionQuery.getDepositAmount().min(modelMultiConditionQuery.getDepositAmount());
            BigDecimal maxDeposit = modelMultiConditionQuery.getDepositAmount().max(modelMultiConditionQuery.getDepositAmount());
            queryWrapper.between(BizModel::getDepositAmount, minDeposit, maxDeposit);
        }

        int pageNum = modelMultiConditionQuery.getPageNum();
        int pageSize = modelMultiConditionQuery.getPageSize();
        Page<BizModel> page = new Page<>(pageNum, pageSize);

        queryWrapper.orderByDesc(BizModel::getId);

        // 执行分页查询
        Page<BizModel> modelMultiConditionPage = carModelService.page(page, queryWrapper);
        PageVo pageVo = new PageVo();
        pageVo.setTotal(modelMultiConditionPage.getTotal());
        pageVo.setList(modelMultiConditionPage.getRecords());
        // 判断是否查询到数据，如果总记录数为0，则返回失败结果
        if (modelMultiConditionPage.getTotal() == 0) {
            return Result.failed("未查询到符合条件的车型数据");
        }
        return Result.success(pageVo);
    }
    @Operation(summary = "根据时间范围查询")
    @PostMapping("/timeRangeQuery")
    public Result timeRangeQuery(@RequestParam(value = "startTime") String startTime,
                                 @RequestParam(value = "endTime") String endTime,
                                 @RequestBody BasePageQuery basePageQuery) {
        LambdaQueryWrapper<BizModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(startTime != null && endTime != null, BizModel::getCreateTime, startTime, endTime);
        queryWrapper.orderByDesc(BizModel::getCreateTime);
        int pageNum = basePageQuery.getPageNum();
        int pageSize = basePageQuery.getPageSize();
        Page<BizModel> page = new Page<>(pageNum, pageSize);
        Page<BizModel> timeRangeQuery = carModelService.page(page, queryWrapper);
        PageVo pageVo = new PageVo();
        pageVo.setTotal(timeRangeQuery.getTotal());
        pageVo.setList(timeRangeQuery.getRecords());
        // 判断是否查询到数据，如果总记录数为0，则返回失败结果
        if (timeRangeQuery.getTotal() == 0) {
            return Result.failed("未查询到符合条件的车型数据");
        }
        return Result.success(pageVo);
    }

    @GetMapping("/type")
    public Result<List> listCarTypes() {
        return Result.success(bizModelService.getCarTypesWithPrices());
    }

    @Operation(summary = "根据车辆ID获取车辆信息")
    @GetMapping("/detail")
    public Result getDetailById(@RequestParam Integer id){
        VehicleDetailQuery vehicleDetailQueries = vehicleService.CarDetail(id);
        System.out.println(vehicleDetailQueries.getServiceFee());
        return Result.success(vehicleDetailQueries);
    }
}
